﻿using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using AutoCADDotNetLibrary;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using NUnitLite;

namespace $safeprojectname$
{
    public class AutoCADTestRunner
    {
        [IdleInitialize(Index = 100)]//最后的最后执行
        [CommandMethod("RunCADTests", CommandFlags.Session)]
        public void RunCADTests()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.SendStringToExecute($"test\n", true, false, false);
        }

        #region CADtest

        //https://github.com/CADbloke/CADtest
        [CommandMethod("test", CommandFlags.Session)]
        public void test()
        {
            if (!AttachConsole(-1))  // Attach to a parent process console
                AllocConsole(); // Alloc a new console if none available

            string directoryPlugin = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string directoryReportUnit = Path.Combine(directoryPlugin, @"ReportUnit");
            Directory.CreateDirectory(directoryReportUnit);
            string fileInputXML = Path.Combine(directoryReportUnit, $"Report-NUnit.xml");
            string fileOutputHTML = Path.Combine(directoryReportUnit, $"Report-NUnit.html");
            string generatorReportUnit = Path.Combine(directoryPlugin, $"ReportUnit.exe");

            string[] nunitArgs = new string[]
                {
                    "--trace=verbose", // Tell me everything
                    "--result=" + fileInputXML
                };

            int errorCount = new AutoRun().Execute(nunitArgs);

            CreateHTMLReport(fileInputXML, fileOutputHTML, generatorReportUnit);

            //打开html
            System.Diagnostics.Process.Start(fileOutputHTML);


            if (errorCount == 0)
            {
                Application.DocumentManager.CloseAll();
                Application.Quit();
            }
        }

        private void CreateHTMLReport(string pFileInputXML, string pFileOutputHTML, string pGeneratorReportUnit)
        {
            if (!File.Exists(pFileInputXML))
                return;

            if (File.Exists(pFileOutputHTML))
                File.Delete(pFileOutputHTML);

            string output = string.Empty;
            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.CreateNoWindow = true;

                    process.StartInfo.FileName = pGeneratorReportUnit;

                    StringBuilder param = new StringBuilder();
                    param.AppendFormat(" \"{0}\"", pFileInputXML);
                    param.AppendFormat(" \"{0}\"", pFileOutputHTML);
                    process.StartInfo.Arguments = param.ToString();

                    process.Start();

                    // read the output to return
                    // this will stop this execute until AutoCAD exits
                    StreamReader outputStream = process.StandardOutput;
                    output = outputStream.ReadToEnd();
                    outputStream.Close();
                }

            }
            catch (System.Exception ex)
            {
                output = ex.Message;
            }
        }

        [DllImport("kernel32.dll")]
        public static extern bool AllocConsole();

        [DllImport("kernel32.dll")]
        private static extern bool AttachConsole(int pid);

        #endregion
    }
}
